package com.uzai.console.service.user.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.entity.WechatUser;
import com.uzai.common.entity.WxpubUser;
import com.uzai.common.enums.MerConfigKeyEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.common.ResponseMsg;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.config.UzaiConsoleSysConfig;
import com.uzai.console.dto.user.wechatuser.TimeVO;
import com.uzai.console.dto.user.wechatuser.WechatUserUpdateDto;
import com.uzai.console.dto.user.wxpubuser.*;
import com.uzai.console.entity.MerBaseConfig;
import com.uzai.console.entity.Merchant;
import com.uzai.console.enums.SmsType;
import com.uzai.console.mapper.*;
import com.uzai.console.service.merchant.MerchantService;
import com.uzai.console.service.user.MarketingRewardsBlackListService;
import com.uzai.console.service.user.WxpubUserService;
import com.uzai.console.service.user.WxpubUserSyncService;
import com.uzai.console.vo.smscode.SmsCodeVo;
import com.uzai.console.vo.user.wechatuser.MinMaxCreateTimeVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class WxpubUserSyncServiceImpl implements WxpubUserSyncService {

    Logger logger = LoggerFactory.getLogger(WxpubUserSyncServiceImpl.class);

    @Autowired
    private WxpubUserMapper wxpubUserMapper;
    @Autowired
    private UserTypeMapper userTypeMapper;
    @Autowired
    private WxpubUserService wxpubUserService;
    @Autowired
    private DeviceWechatInfoMapper deviceWechatInfoMapper;
    @Autowired
    private UzaiConsoleSysConfig uzaiConsoleSysConfig;
    @Autowired
    private MarketingRewardsBlackListService marketingRewardsBlackListService;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private MerBaseConfigMapper merBaseConfigMapper;

//    /**
//     * 查询结果添加群发任务
//     *
//     */
//    @Async("taskExecutor")
//    @Override
//    public void sendMessageToUserSelectedSync(WxpubUserBatchSendMsgDto wxpubUserBatchSendMsgDto) {
//        WxpubUserQuery wxpubUserQuery = wxpubUserBatchSendMsgDto.getWxpubUserQuery();
//        wxpubUserQuery.setMerId(wxpubUserBatchSendMsgDto.getMerId());
//        //查询条件中是否包含机器人id,
//        if (wxpubUserQuery.getDeviceUniqueId() != null) {//条件中带机器人id,则添加到机器人列表中
//            wxpubUserService.groupSendMsgByDeviceUniqueId(wxpubUserBatchSendMsgDto);
//        } else {//如果没有，则查询该运营商所有的机器人
//            DeviceWechatInfoQuery deviceWechatInfoQuery = new DeviceWechatInfoQuery();
//            deviceWechatInfoQuery.setMerId(wxpubUserBatchSendMsgDto.getMerId());
//            List<DeviceWechatInfo> deviceWechatInfoList = deviceWechatInfoMapper.findByList(deviceWechatInfoQuery);
//            if (deviceWechatInfoList != null && deviceWechatInfoList.size() > 0) {
//                for (DeviceWechatInfo deviceWechatInfo : deviceWechatInfoList) {
//                    try {
//                        WxpubUserBatchSendMsgDto wxpubUserBatchSendMsgDto_deviceUniqueId = new WxpubUserBatchSendMsgDto();
//                        wxpubUserBatchSendMsgDto_deviceUniqueId.setMerId(wxpubUserBatchSendMsgDto.getMerId());
//                        wxpubUserBatchSendMsgDto_deviceUniqueId.setWxpubUserGroupSendMsgDto(wxpubUserBatchSendMsgDto.getWxpubUserGroupSendMsgDto());
//                        wxpubUserBatchSendMsgDto_deviceUniqueId.setGroupSendJobParent(wxpubUserBatchSendMsgDto.getGroupSendJobParent());
//                        WxpubUserQuery wxpubUserQuery_deviceUniqueId = new WxpubUserQuery();
//                        BeanUtils.copyProperties(wxpubUserQuery, wxpubUserQuery_deviceUniqueId);
//                        wxpubUserQuery_deviceUniqueId.setDeviceUniqueId(deviceWechatInfo.getId());
//                        wxpubUserBatchSendMsgDto_deviceUniqueId.setWxpubUserQuery(wxpubUserQuery_deviceUniqueId);
//                        wxpubUserService.groupSendMsgByDeviceUniqueId(wxpubUserBatchSendMsgDto_deviceUniqueId);
//                    } catch (Exception e) {
//                        logger.error("-------sendMessageToUserSelectedSync is error; deviceUniqueId={}, error={}", wxpubUserQuery.getDeviceUniqueId(), e.getMessage());
//                    }
//                }
//            }
//        }
//    }
//
//    /**
//     * 查询结果定投筛选
//     *
//     */
//    @Async("taskExecutor")
//    @Override
//    public void optCpcToUserSelected(WxpubUserBatchOptCpcDto wxpubUserBatchOptCpcDto) {
//        if (wxpubUserBatchOptCpcDto.getMerId() == null) {
//            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
//        }
//        WxpubUserOptCpcDto wxpubUserOptCpcDto = wxpubUserBatchOptCpcDto.getWxpubUserOptCpcDto();
//        if (wxpubUserOptCpcDto == null) {
//            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
//        }
//
//        if (wxpubUserOptCpcDto.getCpaId() == null) {
//            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择定投项目");
//        }
//
//        List<WxpubUser> wxpubUserList = wxpubUserMapper.findByList(wxpubUserBatchOptCpcDto.getWxpubUserQuery());
//        if (wxpubUserList != null) {
//            for (WxpubUser wxpubUser : wxpubUserList) {
//                try {
//                    wxpubUserOptCpcDto.setId(wxpubUser.getId());
//                    wxpubUserService.optCpcToOneUser(wxpubUserOptCpcDto);
//                } catch (Exception e) {
//                    logger.error("-------optCpcToOneUser is error userId={}, error={}", wxpubUser.getId(), e.getMessage());
//                    continue;
//                }
//            }
//        }
//
//    }

    /**
     * 查询结果批量修改
     *
     */
    @Async("taskExecutor")
    @Override
    public void batchUpdateToUserSelected(WxpubUserBatchUpdateDto wxpubUserBatchUpdateDto) {

        if (wxpubUserBatchUpdateDto.getMerId() == null) {
           return;
        }

        if (wxpubUserBatchUpdateDto.getWxpubUserUpdateDto() == null) {
           return;
        }

        WxpubUserQuery wxpubUserQuery = wxpubUserBatchUpdateDto.getWxpubUserQuery();
        wxpubUserQuery.setMerId(wxpubUserBatchUpdateDto.getMerId());

        //查询总数
        Integer count = wxpubUserMapper.findCount(wxpubUserQuery);
        //每页个数
        int size = 10;
        if(Tools.getInteger(count) > 0 ){
            int totalPage = count / size + 1; //总页数
            for(int i = totalPage ; i>0;  i--){
                //每个时间段分页查询，每页200个
                Page<WxpubUser> page = new Page<>();
                page.setCurrent(i);
                page.setSize(size);
                List<WxpubUser> wxpubUserList = wxpubUserMapper.findByList(page, wxpubUserQuery);
                if(wxpubUserList != null && wxpubUserList.size() > 0){
                    for(WxpubUser wxpubUser : wxpubUserList) {
                        try {
                            WxpubUserUpdateDto wxpubUserUpdateDto = new WxpubUserUpdateDto();
                            //赋值
                            BeanUtils.copyProperties(wxpubUserBatchUpdateDto.getWxpubUserUpdateDto(), wxpubUserUpdateDto);
                            wxpubUserUpdateDto.setMerId(wxpubUserBatchUpdateDto.getMerId());
                            wxpubUserUpdateDto.setId(wxpubUser.getId());
                            wxpubUserUpdateDto.setLoginToken(wxpubUserBatchUpdateDto.getLoginToken());
                            wxpubUserService.updateToOneUser(wxpubUserUpdateDto);
                            //营销黑名单
                            //marketingRewardsBlackListService.addOrRemoveByFlag(wxpubUser.getMerId(), String.valueOf(wxpubUser.getId()), wxpubUserUpdateDto.getMarketingRewardsBlackListRemark(), wxpubUserUpdateDto.getMarketingRewardsBlackListFlag());
                        } catch (Exception e) {
                            logger.error("-------updateToOneUser is error userId={}, error={}", wxpubUser.getId(), e.getMessage());
                        }

                    }
                }
            }
        }

//        //查询这个机器人的所有会员的最小和最大创建时间-根据创建时间10天内来分段查询
//        MinMaxCreateTimeVo minMaxCreateTimeVo = wxpubUserMapper.findMinAndMaxCreateTime(wxpubUserQuery);
//        //有总数，且最小创建时间有
//        if(minMaxCreateTimeVo != null && Tools.getInteger(count) != 0) {
//            //则循环查询5天内的创建的会员
//            int duration = 5 * 24 * 3600;
//            List<TimeVO> timeVOList = DateUtil.getTimeScope(minMaxCreateTimeVo.getMinCreateTime(), minMaxCreateTimeVo.getMaxCreateTime(), duration);
//            if (timeVOList != null && timeVOList.size() > 0) {
//                for (TimeVO timeVO : timeVOList) {
//                    wxpubUserQuery.setCreateTimeStart(timeVO.getBeginTime());
//                    wxpubUserQuery.setCreateTimeEnd(timeVO.getEndTime());
//
//                    //每个时间段分页查询，每页10个
//                    Page<WxpubUser> page = new Page<>();
//                    int current = 1;
//                    page.setCurrent(current);
//                    page.setSize(10);//最大支持10，如果此时间段数据大于10，则分页查询
//
//                    List<WxpubUser> wxpubUserList = wxpubUserMapper.findByList(page, wxpubUserQuery);
//                    while (wxpubUserList != null && wxpubUserList.size() > 0){
//                        for (WxpubUser wxpubUser : wxpubUserList) {
//                            try {
//                                WxpubUserUpdateDto wxpubUserUpdateDto = new WxpubUserUpdateDto();
//                                //赋值
//                                BeanUtils.copyProperties(wxpubUserBatchUpdateDto.getWxpubUserUpdateDto(), wxpubUserUpdateDto);
//                                wxpubUserUpdateDto.setMerId(wxpubUserBatchUpdateDto.getMerId());
//                                wxpubUserUpdateDto.setId(wxpubUser.getId());
//                                wxpubUserService.updateToOneUser(wxpubUserUpdateDto);
//                            } catch (Exception e) {
//                                logger.error("-------updateToOneUser is error userId={}, error={}", wxpubUser.getId(), e.getMessage());
//                            }
//                            WxpubUserUpdateDto wxpubUserUpdateDto = wxpubUserBatchUpdateDto.getWxpubUserUpdateDto();
//                            marketingRewardsBlackListService.addOrRemoveByFlag(wxpubUser.getMerId(), wxpubUser.getBizUserId(), wxpubUserUpdateDto.getMarketingRewardsBlackListRemark(), wxpubUserUpdateDto.getMarketingRewardsBlackListFlag());
//                        }
//
//                        //再次查询下一页
//                        current ++;
//                        page.setCurrent(current);
//                        wxpubUserList = wxpubUserMapper.findByList(page, wxpubUserQuery);
//                    }
//
//                }
//            }
//        }

    }

    /**
     * 查询结果批量修改
     *
     */
    @Async("taskExecutor")
    @Override
    public void batchUpdateToUserBatch(WxpubUserUpdateBatchDto wxpubUserUpdateBatchDto) {
        if (wxpubUserUpdateBatchDto.getMerId() == null) {
            return;
        }

        if (wxpubUserUpdateBatchDto.getWxpubUserUpdateDto() == null) {
            return;
        }

        List<Long> idList = wxpubUserUpdateBatchDto.getIdList();
        if (idList == null || idList.size() == 0) {
            return;
        }

        if (idList != null && idList.size() > 0) {
            //查询所有机器人
            for(Long id : idList){
                try {
                    WxpubUserUpdateDto wxpubUserUpdateDto = new WxpubUserUpdateDto();
                    //赋值
                    BeanUtils.copyProperties(wxpubUserUpdateBatchDto.getWxpubUserUpdateDto(), wxpubUserUpdateDto);
                    wxpubUserUpdateDto.setMerId(wxpubUserUpdateBatchDto.getMerId());
                    wxpubUserUpdateDto.setId(id);
                    wxpubUserUpdateDto.setLoginToken(wxpubUserUpdateBatchDto.getLoginToken());
                    wxpubUserService.updateToOneUser(wxpubUserUpdateDto);
                } catch (Exception e) {
                    logger.error("-------updateToOneUser is error userId={}, error={}", id, e.getMessage());
                }
            }
        }
    }

    @Override
    public void deleteUserBatch(WxpubUserIdListDto wxpubUserIdListDto) {

        Long merId = wxpubUserIdListDto.getMerId();
        Merchant merchant = merchantService.findByMerId(merId);
        if(merchant == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "运营商不存在");
        }

        //查询运营商短信验证功能信息
        boolean smsCodeFlag = true;
        MerBaseConfig merBaseConfig = merBaseConfigMapper.selectByMerId(merId, MerConfigKeyEnum.SMS_CODE_CONFIG.getValue());
        if (merBaseConfig != null) {
            SmsCodeVo smsCodeVo = JSONObject.parseObject(merBaseConfig.getVal(), SmsCodeVo.class);
            if(smsCodeVo != null && smsCodeVo.getWxpubUserDelBySelected() == 0){ //不需要认证
                smsCodeFlag = false;
            }
        }

        if(smsCodeFlag){
            //如果输入的验证码不是系统通用密码，则需要验证
            if(!uzaiConsoleSysConfig.getDefaultPassword().equals(wxpubUserIdListDto.getCode())){
                //获取存在redis中的验证码
                String codeByRedis = (String) redisTemplate.opsForValue().get(String.format(SmsType.USER_DATA_DELETE.getDesc(), merchant.getMobile()));
                //判断验证码是否过期
                if (StringUtils.isBlank(codeByRedis)){
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.CODE_MISS);
                }
                //验证码是否正确
                if (!codeByRedis.equals(wxpubUserIdListDto.getCode()) && !uzaiConsoleSysConfig.getDefaultPassword().equals(wxpubUserIdListDto.getCode())){
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.CODE_ERR);
                }
                //验证成功，删除验证码
                redisTemplate.delete(String.format(SmsType.USER_DATA_DELETE.getDesc(), merchant.getMobile()));
            }
        }

        //封装批量删除的用户ID
        List<Long> idList = wxpubUserIdListDto.getIdList();
        if (wxpubUserIdListDto.getIdList() != null && wxpubUserIdListDto.getIdList().size() > 0) {
            for (Long id : idList) {
                try {
                    wxpubUserService.deleteUserById(id, wxpubUserIdListDto.getMerId());
                } catch (Exception e) {
                    logger.error("-------delete WxpubUser ById is error userId={}, error={}", id, e.getMessage());
                }
            }
        }
    }

    /**
     * 批量删除下级会员数据（多选框）
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param wxpubUserDeleteSonBatchDto
     * @return null
     */
    public void deleteSonWxworkUserBatch(WxpubUserDeleteSonBatchDto wxpubUserDeleteSonBatchDto){

        Integer identity = wxpubUserDeleteSonBatchDto.getIdentity();
        if(identity == null){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请输入身份参数");
        }

        //封装批量删除的用户ID
        List<Long> idList = wxpubUserDeleteSonBatchDto.getIdList();
        if(idList == null || idList.size() == 0){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择输入的下级会员");
        }
        for (Long id : idList){
            try {
                WxpubUserDeleteSonDto wxpubUserDeleteSonDto = new WxpubUserDeleteSonDto();
                BeanUtils.copyProperties(wxpubUserDeleteSonBatchDto, wxpubUserDeleteSonDto);
                wxpubUserDeleteSonDto.setMerId(wxpubUserDeleteSonBatchDto.getMerId());
                wxpubUserDeleteSonDto.setId(id);
                wxpubUserDeleteSonDto.setIdentity(identity);
                wxpubUserService.deleteSonWxpubUser(wxpubUserDeleteSonDto);
            }catch (Exception e){
                logger.error("-------deleteSonWxpubUser is error userId={}, error={}", id, e.getMessage());
            }
        }
    }

    /**
     * 查询结果批量修改营销策略
     *
     */
    @Async("taskExecutor")
    @Override
    public void updateMarketingRewardByQueryResult(WxpubUserUpdateMarketingRewardByQueryResultDto wxpubUserUpdateMarketingRewardByQueryResultDto) {

        if (wxpubUserUpdateMarketingRewardByQueryResultDto.getMerId() == null) {
            return;
        }

        if (wxpubUserUpdateMarketingRewardByQueryResultDto.getMarketingReward() == null) {
            return;
        }

        WxpubUserQuery wxpubUserQuery = wxpubUserUpdateMarketingRewardByQueryResultDto.getWxpubUserQuery();
        wxpubUserQuery.setMerId(wxpubUserUpdateMarketingRewardByQueryResultDto.getMerId());
        //查询总数
        Integer count = wxpubUserMapper.findCount(wxpubUserQuery);
        //每页个数
        int size = 10;
        if(Tools.getInteger(count) > 0 ){
            int totalPage = count / size + 1; //总页数
            for(int i = totalPage ; i>0;  i--){
                //每个时间段分页查询，每页200个
                Page<WxpubUser> page = new Page<>();
                page.setCurrent(i);
                page.setSize(size);
                List<WxpubUser> wxpubUserList = wxpubUserMapper.findByList(page, wxpubUserQuery);
                if(wxpubUserList != null && wxpubUserList.size() > 0){
                    for(WxpubUser wxpubUser : wxpubUserList) {
                        try {
                            UpdateMarketingRewardDto updateMarketingRewardDto = new UpdateMarketingRewardDto();
                            //赋值
                            BeanUtils.copyProperties(wxpubUserUpdateMarketingRewardByQueryResultDto.getMarketingReward(), updateMarketingRewardDto);
                            updateMarketingRewardDto.setMerId(wxpubUserUpdateMarketingRewardByQueryResultDto.getMerId());
                            updateMarketingRewardDto.setId(wxpubUser.getId());
                            updateMarketingRewardDto.setMarketingReward(wxpubUserUpdateMarketingRewardByQueryResultDto.getMarketingReward());
                            wxpubUserService.updateMarketingReward(updateMarketingRewardDto);
                        } catch (Exception e) {
                            logger.error("-------updateMarketingReward is error userId={}, error={}", wxpubUser.getId(), e.getMessage());
                        }
                    }
                }
            }
        }
    }

}
